<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">日喀则旅游大数据服务平台</h3>
      </div>
      <el-tabs v-model="activeName" class="login-tabs" @tab-click="handleClick">
        <el-tab-pane label="密码登录" name="password">
          <el-form-item prop="username">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="账号"
              name="username"
              type="text"
              tabindex="1"
              auto-complete="on"
            />
          </el-form-item>

          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="密码"
              name="password"
              tabindex="2"
              auto-complete="on"
              @keyup.enter.native="handleLogin"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <div style="display: flex;position: relative;">
            <el-form-item class="captForm">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                v-model="loginForm.captcha"
                class="captInput"
                name="capt"
                tabindex="3"
                auto-complete="on"
                placeholder="验证码"
              />
            </el-form-item>
            <img
              class="code-img"
              :src="imgCodeObj.codeImg"
              @click="getCaptchaImg"
            >

          </div>

          <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @keydown.enter="keyDown()" @keyup.enter.native="handleLogin" @click.native.prevent="handleLogin">登录</el-button>
        </el-tab-pane>
        <el-tab-pane label="手机登录" name="phone">
          <el-form ref="loginForm2" :model="loginForm2" :rules="loginRules2" auto-complete="on" label-position="left">
            <el-form-item prop="phone">
              <span class="svg-container">
                <svg-icon icon-class="user" />
              </span>
              <el-input
                ref="phone"
                v-model="loginForm2.phone"
                placeholder="账号"
                name="phone"
                type="text"
                tabindex="1"
                auto-complete="on"
              />
            </el-form-item>
            <el-form-item>
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                v-model="loginForm2.code"
                name="code"
                tabindex="3"
                auto-complete="on"
                placeholder="验证码"
              />
              <span class="code-btn" @click="sendCode">
                {{
                  isSending
                    ? "发送中..."
                    : countdown > 0
                      ? `${countdown}秒后重试`
                      : "发送验证码"
                }}
              </span>
              <!-- <el-button class="code-btn" type="text">获取验证码</el-button> -->
            </el-form-item>

          </el-form>
          <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @keydown.enter="keyDown()" @keyup.enter.native="handleLogin" @click.native.prevent="handleLogin">登录</el-button>
        </el-tab-pane>
      </el-tabs>

      <!-- <div class="tips">
        <span style="margin-right:20px;">username: 18888888888</span>
        <span> password: 123123</span>
      </div> -->

    </el-form>
  </div>
</template>

<script>
// import { validUsername } from '@/utils/validate'
import { getCaptcha, getCode } from '@/api/common'
export default {
  name: 'Login',
  data() {
    // const validateUsername = (rule, value, callback) => {
    //   if (!validUsername(value)) {
    //     callback(new Error('Please enter the correct user name'))
    //   } else {
    //     callback()
    //   }
    // }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        captcha: ''
      },
      loginForm2: {
        phone: '',
        code: ''
      },
      imgCodeObj: {
        codeId: '',
        codeImg: ''
      },
      loginRules: {
        // validator: validateUsername
        username: [{ required: true, trigger: 'blur' }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        captcha: [{ required: true, trigger: 'blur' }]
      },
      loginRules2: {
        // validator: validateUsername
        phone: [{ required: true, trigger: 'blur' }],
        code: [{ required: true, trigger: 'blur' }]
      },
      activeName: 'password',
      isSending: false,
      countdown: 0,
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
        console.log(this.redirect, route.query, route, '--------------this.redirect')
      },
      immediate: true
    }
  },
  created() {
    this.getCaptchaImg()
  },
  mounted() {
    window.addEventListener('keydown', this.keyDown)
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false)
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event)
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    keyDown(e) {
      if (e.keyCode === 13) {
        this.handleLogin()
      }
    },
    startCountdown() {
      this.countdown = 60
      const timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    },
    sendCode() {
      if (this.countdown > 0 || this.isSending) {
        return // 防止重复点击发送
      }
      getCode({ phone: this.loginForm2.phone }).then(res => {
        console.log(res, '--------------------------getCaptcha')
        if (res.status == 200) {
          this.isSending = false
          this.startCountdown()
        }
      })
      // console.log(res, "--------------getSmsCode");
    },
    getCaptchaImg() {
      getCaptcha().then(res => {
        this.imgCodeObj.codeImg = res.img
        this.imgCodeObj.codeId = res.key
        console.log(res, '--------------------------getCaptcha')
      })
    },
    handleLogin() {
      // 重构：提取公共验证逻辑到一个函数
      const validateAndHandle = (loginForm, action) => {
        this.loading = true
        this.$store.dispatch(action, { ...loginForm }).then(() => {
          this.handlePermissions()
        }).catch(error => {
          console.error('登录失败:', error)
          this.loading = false
          this.getCaptchaImg()
        })
      }

      if (this.activeName === 'password') {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            validateAndHandle({ ...this.loginForm, key: this.imgCodeObj.codeId }, 'user/login')
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs.loginForm2.validate(valid => {
          if (valid) {
            validateAndHandle(this.loginForm2, 'user/codeLogin')
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },

    handlePermissions() {
      const roles = JSON.parse(localStorage.getItem('permissions')) || []
      const routeMap = new Map([
        ['dashbord', '/'],
        ['dict', '/authority/account'],
        ['sub-task-report', '/dataFilling/workOrder'],
        ['sub-task-review1', '/dataFilling/workReview'],
        ['sub-task-review2', '/dataFilling/workReview']
      ])

      // 优化权限判断逻辑
      const targetRoute = roles.find(role => routeMap.has(role)) || '/'
      this.$router.push({ path: routeMap.get(targetRoute) })

      this.loading = false
      this.getCaptchaImg()
    }
    // handleLogin() {
    //   if (this.activeName === 'password') {
    //     this.$refs.loginForm.validate(valid => {
    //       if (valid) {
    //         this.loading = true
    //         console.log(this.loginForm, '-----------------------------captcha')
    //         this.$store.dispatch('user/login', { ...this.loginForm, key: this.imgCodeObj.codeId }).then(() => {
    //           const roles = JSON.parse(localStorage.getItem('permissions'))
    //           console.log(roles, '----------------roles')
    //           roles.forEach(ele => {
    //             if (ele === 'dashbord') {
    //               this.$router.push({ path: '/' })
    //             } else if (ele === 'dict') {
    //               this.$router.push({ path: '/authority/account' })
    //             } else if (ele === 'sub-task-report') {
    //               this.$router.push({ path: '/dataFilling/workOrder' })
    //             } else if (ele === 'sub-task-review1' || ele === 'sub-task-review2') {
    //               this.$router.push({ path: '/dataFilling/workReview' })
    //             }
    //           })
    //           // this.$router.push({ path: this.redirect || '/' })
    //           // this.$router.push({ path: '/' })
    //           this.loading = false
    //           this.getCaptchaImg()
    //         }).catch(() => {
    //           this.loading = false
    //           this.getCaptchaImg()
    //         })
    //       } else {
    //         console.log('error submit!!')
    //         return false
    //       }
    //     })
    //   } else {
    //     this.$refs.loginForm2.validate(valid => {
    //       if (valid) {
    //         this.loading = true
    //         this.$store.dispatch('user/codeLogin', { ...this.loginForm2 }).then(() => {
    //           const roles = JSON.parse(localStorage.getItem('permissions'))
    //           console.log(roles, '----------------roles')
    //           roles.forEach(ele => {
    //             if (ele === 'dashbord') {
    //               this.$router.push({ path: '/' })
    //             } else if (ele === 'dict') {
    //               this.$router.push({ path: '/authority/account' })
    //             } else if (ele === 'sub-task-report') {
    //               this.$router.push({ path: '/dataFilling/workOrder' })
    //             } else if (ele === 'sub-task-review1' || ele === 'sub-task-review2') {
    //               this.$router.push({ path: '/dataFilling/workReview' })
    //             }
    //           })
    //           // this.$router.push({ path: this.redirect || '/' })
    //           // this.$router.push({ path: '/' })
    //           this.loading = false
    //           this.getCaptchaImg()
    //         }).catch(() => {
    //           this.loading = false
    //           this.getCaptchaImg()
    //         })
    //       } else {
    //         console.log('error submit!!')
    //         return false
    //       }
    //     })
    //   }
    // }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .code-img {
    position: absolute;
    top: 5px;
    right: 5px;
    cursor: pointer;
    width: 140px;
    height: 40px;
  }
  .code-btn {
    color: #66b1ff;
    position: absolute;
    cursor: pointer;
    top: 7px;
    right: 20px;
  }
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  .captInput {
    width: 64% !important;
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  .captForm {
    width: 300px;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
<style scoped>
::v-deep .el-tabs__item {
  color: #ffff;
  font-size: 18px;
}
::v-deep .el-tabs__content {
  overflow: visible;
}
::v-deep .el-tabs__item.is-active {
  color: #66b1ff;
}
::v-deep .el-tabs__nav-wrap::after {
  height: 0;
}
</style>

